import { invoke } from '@tauri-apps/api/core';
import { VideoFile, ProcessTask, ProcessOptions } from '@/types/video';
import { TauriApiResponse } from '@/types/api';

export const videoService = {
  // File selection and management
  async selectFiles(): Promise<TauriApiResponse<string[]>> {
    try {
      return await invoke('video_select_files');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to select files',
      };
    }
  },

  async selectFolder(): Promise<TauriApiResponse<string>> {
    try {
      return await invoke('video_select_folder');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to select folder',
      };
    }
  },

  async getVideoInfo(path: string): Promise<TauriApiResponse<VideoFile>> {
    try {
      return await invoke('video_get_info', { path });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get video info',
      };
    }
  },

  // Video processing
  async processVideo(
    inputPath: string,
    outputPath: string,
    options: ProcessOptions
  ): Promise<TauriApiResponse<ProcessTask>> {
    try {
      return await invoke('video_process', { inputPath, outputPath, options });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to process video',
      };
    }
  },

  async batchProcess(
    inputPaths: string[],
    outputPath: string,
    options: ProcessOptions
  ): Promise<TauriApiResponse<ProcessTask[]>> {
    try {
      return await invoke('video_batch_process', { inputPaths, outputPath, options });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to batch process videos',
      };
    }
  },

  // Task management
  async getProcessStatus(taskId: string): Promise<TauriApiResponse<ProcessTask>> {
    try {
      return await invoke('video_get_task_status', { taskId });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get task status',
      };
    }
  },

  async cancelProcess(taskId: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_cancel_task', { taskId });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to cancel task',
      };
    }
  },

  async pauseProcess(taskId: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_pause_task', { taskId });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to pause task',
      };
    }
  },

  async resumeProcess(taskId: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_resume_task', { taskId });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to resume task',
      };
    }
  },

  // Utility functions
  async generateThumbnail(
    videoPath: string,
    outputPath: string,
    timestamp: number
  ): Promise<TauriApiResponse<string>> {
    try {
      return await invoke('video_generate_thumbnail', { videoPath, outputPath, timestamp });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to generate thumbnail',
      };
    }
  },

  async extractAudio(
    videoPath: string,
    outputPath: string,
    format: string
  ): Promise<TauriApiResponse<string>> {
    try {
      return await invoke('video_extract_audio', { videoPath, outputPath, format });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to extract audio',
      };
    }
  },

  async getVideoFormats(): Promise<TauriApiResponse<string[]>> {
    try {
      return await invoke('video_get_supported_formats');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get video formats',
      };
    }
  },

  async getAudioFormats(): Promise<TauriApiResponse<string[]>> {
    try {
      return await invoke('video_get_audio_formats');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get audio formats',
      };
    }
  },

  // Validation helpers
  validateVideoFile(file: File): boolean {
    const supportedTypes = [
      'video/mp4',
      'video/avi',
      'video/mov',
      'video/mkv',
      'video/wmv',
      'video/flv',
      'video/webm',
      'video/3gp',
    ];
    return supportedTypes.includes(file.type);
  },

  formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  },

  formatDuration(seconds: number): string {
    const hrs = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hrs > 0) {
      return `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  },

  getFileExtension(filename: string): string {
    return filename.split('.').pop()?.toLowerCase() || '';
  },

  generateOutputFilename(
    inputPath: string,
    suffix: string = '_processed',
    newExtension?: string
  ): string {
    const pathParts = inputPath.split('/');
    const filename = pathParts[pathParts.length - 1];
    const nameWithoutExt = filename.substring(0, filename.lastIndexOf('.'));
    const extension = newExtension || filename.substring(filename.lastIndexOf('.'));

    return `${nameWithoutExt}${suffix}${extension}`;
  },

  // Progress monitoring
  async subscribeToProgress(
    taskId: string,
    callback: (progress: any) => void
  ): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_subscribe_progress', { taskId, callback });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to subscribe to progress',
      };
    }
  },

  async unsubscribeFromProgress(taskId: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_unsubscribe_progress', { taskId });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to unsubscribe from progress',
      };
    }
  },

  async getAllTasks(): Promise<TauriApiResponse<ProcessTask[]>> {
    try {
      return await invoke('video_get_all_tasks');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get all tasks',
      };
    }
  },

  async clearCompletedTasks(): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_clear_completed_tasks');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to clear completed tasks',
      };
    }
  },

  async getOutputDirectory(): Promise<string> {
    try {
      const result = await invoke('video_get_output_directory');
      return result as string;
    } catch (error) {
      // Fallback to default directory
      return './output';
    }
  },

  async setOutputDirectory(path: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('video_set_output_directory', { path });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to set output directory',
      };
    }
  },

  // Real-time progress tracking
  createProgressSubscription(_taskId: string, onProgress: (data: any) => void): () => void {
    // Mock implementation for frontend development
    let interval: NodeJS.Timeout | null = null;
    let currentProgress = 0;

    const startProgress = () => {
      interval = setInterval(() => {
        currentProgress += Math.random() * 10;
        if (currentProgress >= 100) {
          currentProgress = 100;
          onProgress({
            percentage: 100,
            currentStep: '处理完成',
            timeRemaining: 0,
          });
          if (interval) clearInterval(interval);
        } else {
          onProgress({
            percentage: currentProgress,
            currentStep: getRandomStep(currentProgress),
            timeRemaining: Math.max(0, (100 - currentProgress) * 2),
          });
        }
      }, 500);
    };

    // Start after a short delay
    setTimeout(startProgress, 100);

    // Return cleanup function
    return () => {
      if (interval) {
        clearInterval(interval);
        interval = null;
      }
    };
  },
};

// Helper function for mock progress steps
function getRandomStep(progress: number): string {
  const steps = [
    '初始化处理器...',
    '读取输入文件...',
    '分析视频属性...',
    '开始编码处理...',
    '应用视频滤镜...',
    '处理音频轨道...',
    '优化输出质量...',
    '生成输出文件...',
    '验证文件完整性...',
    '清理临时文件...',
  ];

  const stepIndex = Math.floor((progress / 100) * steps.length);
  return steps[Math.min(stepIndex, steps.length - 1)];
}
